package com.ymm.filter;

import com.alibaba.fastjson.JSON;
import com.ymm.domain.entity.LoginUser;
import com.ymm.domain.vo.ResponseResult;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.enums.RedisKeyEnum;
import com.ymm.utils.JwtUtil;
import com.ymm.utils.RedisCache;
import com.ymm.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token,获取id
        String userid = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            // 因为异常的的统一处理是针对controller层的,所以不能抛出异常
            // 直接响应数据json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        // 从redis里面获取user
        LoginUser loginUser = redisCache.getCacheObject(RedisKeyEnum.HT_USER_KEY + userid);
        if (Objects.isNull(loginUser)) {
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_OUT_TIME);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        // 将用户信息存放在SecurityContextHolder里面
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
